package com.hotkid.ceo.jetpack.myjetpackmvvm.ui.register

import android.view.View
import com.hotkid.ceo.jetpack.myjetpackmvvm.base.BaseVmActivity
import com.hotkid.ceo.jetpack.myjetpackmvvm.databinding.ActivityRegisterBinding
import com.hotkid.ceo.jetpack.myjetpackmvvm.util.setOnclickNoRepeat
import com.yechaoa.yutilskt.ToastUtil
import com.yechaoa.yutilskt.YUtils

/**
 * ClassName:Regsister
 * Package:com.hotkid.ceo.jetpack.myjetpackmvvm.ui.register
 * Description:
 * @date:2021/3/25 11:05 PM
 * @author:774169396@qq.com
 */
class RegsisterActivity : BaseVmActivity<ActivityRegisterBinding, RegisterViewModel>() {
    override fun veiwModelClass() = RegisterViewModel::class.java
    override fun getViewBinding() = ActivityRegisterBinding.inflate(layoutInflater)

    override fun initView() {
        mBinding.btnRegister.setOnclickNoRepeat {
            attemptRegister()
        }
    }

    private fun attemptRegister() {
        YUtils.closeSoftKeyboard()
        mBinding.etUsername.error = null
        mBinding.etPassword.error = null
        mBinding.etRepassword.error = null


        val username = mBinding.etUsername.text.toString().trim()
        val password = mBinding.etPassword.text.toString().trim()
        val repassword = mBinding.etRepassword.text.toString().trim()

        var cancel = false
        var focueView: View? = null
        if (repassword.isEmpty()) {
            mBinding.etRepassword.error = "确认密码不能为空"
            focueView = mBinding.etRepassword
            cancel = true
        }

        if (password.isEmpty()) {
            mBinding.etRepassword.error = "确认密码不能为空"
            focueView = mBinding.etPassword
            cancel = true
        }

        if (password != repassword) {
            mBinding.etRepassword.error = "两次密码不一致"
            focueView = mBinding.etPassword
            cancel = true
        }

        if (username.isEmpty()) {
            mBinding.etUsername.error = "账号不能为空"
            focueView = mBinding.etUsername
            cancel = true
        }

        if (cancel) focueView?.requestFocus() else
            doRegister(username, password, repassword)

    }

    private fun doRegister(username: String, password: String, repassword: String) {
        YUtils.showLoading(this, "加载中")
        mViewModel.register(username, password, repassword)
    }

    override fun observe() {
        super.observe()
        mViewModel.registerState.observe(this, {
            YUtils.hideLoading()
            if (it) {
                ToastUtil.show("注册成功，请登录")
                finish()
            } else {
                ToastUtil.show("注册失败")
            }
        })
    }
}